package semafori;

public class MailBox {

	private int in, out, len;
	private int n;
	private int[] buffer;
	private SemaforoContatore mutex, full, empty;

	public MailBox(int n) {
		this.n = n;
		buffer = new int[n];
		in = 0;
		out = 0;
		len = 0;
		mutex = new SemaforoContatore(1);
		full = new SemaforoContatore(0);
		empty = new SemaforoContatore(n);
	}

	public void put(int item) {
		empty.P();
		mutex.P();
		buffer[in] = item;
		in = (in + 1) % n;
		len++;
		System.out.println("Producer" + Thread.currentThread().getName()+ "put item: " + item);
		mutex.V();
		full.V();
	}// put

	public int get() {
		full.P();
		mutex.P();
		int item = buffer[out];
		out = (out + 1) % n;
		len--;
		System.out.println("Consumer " + Thread.currentThread().getName()+ " got item: " + item);
		mutex.V();
		empty.V();
		return item;
	}// get

}
